package com.youxin.admin.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.youxin.admin.annotation.LoginUser;
import com.youxin.admin.annotation.RequirePermissions;
import com.youxin.admin.auth.domain.ChatUserDto;
import com.youxin.admin.auth.domain.PassChangeDto;
import com.youxin.admin.auth.domain.UserSearchParam;
import com.youxin.admin.auth.model.User;
import com.youxin.admin.auth.service.ChatUserService;
import com.youxin.admin.auth.service.PermissionService;
import com.youxin.admin.auth.util.GoogleAuthenticator;
import com.youxin.admin.model.SysUser;
import com.youxin.base.BaseResultCode;
import com.youxin.base.TPage;
import com.youxin.base.TResult;
import com.youxin.utils.MD5Util;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Validated
@RestController
@RequestMapping("auth/user")
public class UserController {

    @Resource
    private PermissionService permissionService;



    @Resource
    private ChatUserService chatUserService;

    /**
     * 后台菜单列表
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/permission/info", method = RequestMethod.GET)
    @ResponseBody
    public TResult<Map<String, Object>> getUserInfo(@ApiIgnore @LoginUser(isFull = false) SysUser user) throws Exception {
        Map<String, Object> map = generateUserInfo(user.getUserName());
        return TResult.success(map);

    }

    @PostMapping(value = "/addUser")
    //@RequiresPermissions("userpermission:add")
    public TResult<String> addUser(@RequestBody User user) {
        boolean flag = chatUserService.insert(user);
        return TResult.success();
    }

    /**
     * 单个用户信息
     * @param id
     * @return
     */
    @GetMapping(value = "get/{id}")
    public TResult<User> get(@PathVariable Integer id) {
        User user = chatUserService.selectById(id);
        user.setPassword(null);
        user.setAuthKey(null);
        return TResult.success(user);
    }

    @PutMapping(value = "/{id}")
    //@RequiresPermissions("userpermission:del")
    public TResult<String> del(@PathVariable int id) {
        chatUserService.deleteById(id);
        return TResult.success();
    }

    @PutMapping(value = "/update")
    //@RequiresPermissions("userpermission:edit")
    public TResult<String> update(@RequestBody User user) {
        chatUserService.updateById(user);
        return TResult.success();
    }

    @PostMapping(value = "pass/update")
    public TResult<String> updatePassword(@ApiIgnore @LoginUser(isFull = false) SysUser user,@RequestBody PassChangeDto passChangeDto) {
        String pass =  MD5Util.md5Salt(passChangeDto.getOldPassword(), user.getUserName(),1);
        User userInfo = chatUserService.getUserByUsername(user.getUserName());
        if (!userInfo.getPassword().equals(pass)) {
            return TResult.build(BaseResultCode.COMMON_FAIL, "密码不正确");
        }
        String newPass = MD5Util.md5Salt(passChangeDto.getNewPassword(), user.getUserName(),1);
        userInfo.setPassword(newPass);
        chatUserService.updateById(userInfo);
        return TResult.success();
    }

    //@RequiresPermissions("userpermission:resetPwd")
    @GetMapping(value = "pass/reset/{userName}")
    public TResult<String> overwritePass(@ApiIgnore @LoginUser(isFull = false) SysUser sysUser,@PathVariable String userName) {
        if ("admin".equalsIgnoreCase(userName)) {
            return TResult.build(BaseResultCode.COMMON_FAIL, "超级管理员不能重置密码");
        }

        if (sysUser.getUserName().equalsIgnoreCase(userName)) {
            return TResult.build(BaseResultCode.COMMON_FAIL, "不能重置自身密码");
        }

        User user = chatUserService.getUserByUsername(userName);
        if (user == null) {
            return TResult.build(BaseResultCode.COMMON_FAIL, "用户不存在");
        }
        String pass = MD5Util.MD5("123456", "utf-8");
        String newPass = MD5Util.md5Salt(pass, user.getUsername(),1);
        user.setPassword(newPass);
        chatUserService.updateById(user);
        return TResult.success();

    }

    @GetMapping(value = "/page")
    @RequirePermissions(value = "userList")
    public TResult<TPage<User>> listPage(UserSearchParam userSearchParam) {
        //Page page = new Page(pageNo,pageSize);
        QueryWrapper<User> condition = new QueryWrapper<>();
        if (!StringUtils.isEmpty(userSearchParam.getUsername())) {
            condition.like("name", userSearchParam.getUsername());
        }
        condition.select("id", "username", "name", "sex", "description");
        IPage<User> page = chatUserService.selectByPage(new Page<>(userSearchParam.getCurrentPage(), userSearchParam.getShowCount()), condition);
        return TResult.success(TPage.page(page.getRecords(), page.getTotal()));
    }

    @GetMapping(value = "code/{id}")
    //@RequiresPermissions("authCode:show")
    public TResult<String> getAuthCode(@PathVariable Integer id) {
        User user = chatUserService.selectById(id);
        if (user == null || StringUtils.isEmpty(user.getAuthKey())) {
            return TResult.build(BaseResultCode.COMMON_FAIL, "尚未绑定google认证，请先绑定");
        }
        String qrData = GoogleAuthenticator.getQRBarcodeURL(user.getUsername(), "laile.com", user.getAuthKey());
        return TResult.success(qrData);
    }

    @PostMapping(value = "code/gen/{id}")
    //@RequiresPermissions("userpermission:codeGen")
    public TResult genCode(@PathVariable Integer id) {
        User user = chatUserService.selectById(id);
        String secret = GoogleAuthenticator.genSecret();
        user.setAuthKey(secret);
        chatUserService.updateById(user);
        return TResult.success();
    }

    /**
     * 后台用户列表
     *
     * @return
     */
    @PostMapping(value = "userList")
    //@RequiresPermissions("userpermission:userList")
    public TResult<TPage<List<ChatUserDto>>> userList(@RequestBody ChatUserDto chatUserDto, Integer currentPage, Integer showCount) {
        return TResult.success(chatUserService.selectChatUserList(chatUserDto, currentPage, showCount));
    }

    /**
     * 生成前端需要的用户信息，包括：
     * 1. token
     * 2. Vue Router
     * 3. 用户角色
     * 4. 用户权限
     * 5. 前端系统个性化配置信息
     *
     * @param
     * @param user 用户信息
     * @return UserInfo
     */
    private Map<String, Object> generateUserInfo(String userName) {

        return this.permissionService.generateUserInfo(userName);
    }



}
